package com.lxw.redis.study.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxw.redis.study.core.MyResponse;
import com.lxw.redis.study.entity.Emp;
import com.lxw.redis.study.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    EmpService empService;

    /**
     * 新增
     *
     * @param emp
     * @return
     */
    @PostMapping("/emp")
    public MyResponse insert(@RequestBody Emp emp) {
        empService.insert(emp);
        String msg = emp.getMsg();
        if (StringUtils.isEmpty(msg)) {
            msg = "新增成功";
        }
        return MyResponse.success().setMessage(msg);
    }

    /**
     * 根据主键删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/emp/{id}")
    public MyResponse deleteByPrimaryKey(@PathVariable("id") Integer id) {
        empService.deleteByPrimaryKey(id);
        return MyResponse.success().setMessage("删除成功");
    }

    /**
     * 根据主键更新
     *
     * @param emp
     * @return
     */
    @PutMapping("/emp")
    public MyResponse update(@RequestBody Emp emp) {
        empService.update(emp);
        String msg = emp.getMsg();
        if (StringUtils.isEmpty(msg)) {
            msg = "修改成功";
        }
        return MyResponse.success().setMessage(msg);
    }

    /**
     * 根据主键查找
     *
     * @param id 主键
     * @return
     */
    @GetMapping("/emp/{id}")
    public MyResponse selectByPrimaryKey(@PathVariable("id") Integer id) {
        Emp emp = empService.selectByPrimaryKey(id);
        return MyResponse.success(emp);
    }

    /**
     * 分页查询
     *
     * @param param
     * @return
     */
    @PostMapping("/getEmpListByPage")
    public MyResponse selectList(@RequestBody Emp param) {
        Integer currentPage = param.getCurrentPage();
        Integer pageSize = param.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        List<Emp> emps = empService.selectList(param);
        return MyResponse.success(new PageInfo<>(emps));
    }

}
